﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UnitySceneCamera : MonoBehaviour
{
    public static UnitySceneCamera instance;

    private void Awake()
    {
        instance = this;
    }

    private Vector3 centerPos;//围绕的中心点
    private Transform tf;//自己的transform
    public float distance2centerPos = 3f;//到中心点的距离
    private Vector3 targetPos;//摄像机要去的目标点

    //设置中心点的方法
    public void SetCenterPos(Vector3 centerPos)
    {
        this.centerPos = centerPos;
        targetPos = centerPos - tf.forward * distance2centerPos;//算出目标点
    }

    private void Start()
    {
        tf = transform;
        targetPos = transform.position;
    }

    // Update is called once per frame
    private void Update()
    {
        //如果用户按下Alt+左键
        if (Input.GetKey(KeyCode.LeftAlt) && Input.GetKey(KeyCode.Mouse0))
        {
            //获取鼠标的滑动量
            float mosueX = Input.GetAxis("Mouse X");
            float mosueY = Input.GetAxis("Mouse Y");
            //水平围绕旋转
            tf.RotateAround(centerPos, Vector3.up, 120f * Time.deltaTime * mosueX);
            //垂直围绕旋转
            tf.RotateAround(centerPos, tf.right, -120f * Time.deltaTime * mosueY);
            targetPos = tf.position;
        }
        /*滚轮前进后退*/
        float mouseScroll = Input.GetAxis("Mouse ScrollWheel");
        targetPos +=
            transform.TransformDirection((Vector3.forward * 500 * Time.deltaTime * mouseScroll));

        //插值到目标点
        if ((targetPos - transform.position).sqrMagnitude > 0.001f)
        {
            transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime * 8);
        }

        if (Input.GetKeyDown(KeyCode.F))
        {
            SetCenterPos(Selector.CurrentRenderer.transform.position);
        }
    }
}